import React, { useRef, useEffect, useState } from "react";
import { downloadImage } from "../services/memeService";
import { generateGifFromServer } from "../services/api";
import { saveAs } from "file-saver";

const MemeCanvas = ({
  image,
  textElements, // 接收文本元素数组
  selectedTextId, // 接收当前选中的文本ID
  onSelectText, // 接收选择文本的回调
  onTextDrag, // 接收文本拖动的回调
  onAddText, // 接收添加文本的回调
  onDeleteText, // 接收删除文本的回调
  font,
  color,
  size,
  stickers,
  filter,
  onCanvasClick,
  onGenerate,
  generating,
  meme,
  onStickerDrag,
  onStickerSizeChange,
  onStickerRotationChange,
}) => {
  const canvasRef = useRef(null);
  const originalImageRef = useRef(null); // 添加引用来存储原始图像
  const [generatingGif, setGeneratingGif] = useState(false);
  const [previewGif, setPreviewGif] = useState(null); // 存储预览GIF的URL

  // 拖拽状态
  const [dragging, setDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const [isDraggingSticker, setIsDraggingSticker] = useState(false);
  const [selectedStickerIndex, setSelectedStickerIndex] = useState(null);
  const [isResizingSticker, setIsResizingSticker] = useState(false);
  const [isRotatingSticker, setIsRotatingSticker] = useState(false);
  const [resizeStartSize, setResizeStartSize] = useState(0);
  const [rotateStartAngle, setRotateStartAngle] = useState(0);

  // 可用的文字动画效果
  const textAnimationOptions = [
    { value: "bounce", label: "弹跳效果" },
    { value: "wave", label: "波浪效果" },
    { value: "shake", label: "抖动效果" },
    { value: "zoom", label: "缩放效果" },
    { value: "rotate", label: "旋转效果" },
    { value: "fade", label: "淡入淡出" },
  ];

  // 当用户切换动画类型时，清除预览
  useEffect(() => {
    if (previewGif) {
      setPreviewGif(null);
    }
  }, [textElements]);

  // 当previewGif变化时，如果从预览返回编辑，需要重新绘制画布
  useEffect(() => {
    if (!previewGif) {
      resizeCanvas();
    }
  }, [previewGif]);

  // 当图像加载时设置画布尺寸
  useEffect(() => {
    if (image) {
      originalImageRef.current = image;
      resizeCanvas();

      // 添加窗口大小变化监听，确保画布尺寸随窗口变化而调整
      const handleResize = () => {
        resizeCanvas();
      };

      window.addEventListener("resize", handleResize);

      // 清理函数
      return () => {
        window.removeEventListener("resize", handleResize);
      };
    } else {
      // 即使没有图片也创建空白画布
      const canvas = canvasRef.current;
      if (canvas) {
        canvas.width = 500;
        canvas.height = 400;
        const ctx = canvas.getContext("2d");
        ctx.fillStyle = "#f5f5f5";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
      }
    }
  }, [image]);

  // 当文字样式或内容改变时重绘画布
  useEffect(() => {
    drawCanvas();
  }, [image, textElements, stickers, filter, selectedTextId]);

  // 添加图像加载事件监听
  useEffect(() => {
    if (meme && meme.url) {
      const img = new Image();
      img.onload = () => {
        originalImageRef.current = img;
        resizeCanvas();
      };
      img.onerror = () => {
        console.error("Failed to load image");
      };
      img.src = meme.url;
    }
  }, [meme]);

  // 设置鼠标事件监听
  useEffect(() => {
    // 仅在非预览模式下添加事件监听
    if (previewGif) return;

    const canvas = canvasRef.current;
    if (!canvas || !image) return;

    // 鼠标按下事件处理函数
    const handleMouseDown = (e) => {
      if (!image) return;

      const rect = canvas.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      // 计算缩放比例
      const scaleX = canvas.width / rect.width;
      const scaleY = canvas.height / rect.height;

      // 在画布坐标系中的位置
      const canvasX = x * scaleX;
      const canvasY = y * scaleY;

      // 检查是否点击在文字上
      let clickedTextId = null;

      // 先检查是否点击了现有文本
      for (const textElem of textElements) {
        if (isPointInText(canvasX, canvasY, textElem)) {
          clickedTextId = textElem.id;
          break;
        }
      }

      if (clickedTextId) {
        // 选中当前文本
        onSelectText(clickedTextId);

        // 开始拖拽文字
        setDragging(true);
        const textElem = textElements.find((elem) => elem.id === clickedTextId);
        setDragOffset({
          x: canvasX / scaleX - textElem.x / scaleX,
          y: canvasY / scaleY - textElem.y / scaleY,
        });
        e.preventDefault();
      } else {
        // 检查是否点击在贴图上
        const ctx = canvas.getContext("2d");
        ctx.font = "30px serif"; // 使用默认字体大小进行检测

        for (let i = stickers.length - 1; i >= 0; i--) {
          const sticker = stickers[i];
          const metrics = ctx.measureText(sticker.emoji);
          const stickerWidth = metrics.width;
          const stickerHeight = sticker.size;

          // 计算贴图的旋转后的边界框
          const centerX = sticker.x + stickerWidth / 2;
          const centerY = sticker.y - stickerHeight / 2;
          const angle = (sticker.rotation * Math.PI) / 180;

          // 检查是否点击在调整大小的控制点上
          const resizeHandleX =
            centerX + Math.cos(angle) * (stickerWidth / 2 + 15);
          const resizeHandleY =
            centerY + Math.sin(angle) * (stickerWidth / 2 + 15);
          const resizeDistance = Math.sqrt(
            Math.pow(canvasX - resizeHandleX, 2) +
              Math.pow(canvasY - resizeHandleY, 2)
          );

          // 检查是否点击在旋转的控制点上
          const rotateHandleX =
            centerX + Math.cos(angle + Math.PI / 2) * (stickerWidth / 2 + 25);
          const rotateHandleY =
            centerY + Math.sin(angle + Math.PI / 2) * (stickerWidth / 2 + 25);
          const rotateDistance = Math.sqrt(
            Math.pow(canvasX - rotateHandleX, 2) +
              Math.pow(canvasY - rotateHandleY, 2)
          );

          // 检查点击位置是否在贴图范围内（考虑旋转）
          const dx = canvasX - centerX;
          const dy = canvasY - centerY;
          const rotatedX = dx * Math.cos(-angle) - dy * Math.sin(-angle);
          const rotatedY = dx * Math.sin(-angle) + dy * Math.cos(-angle);

          if (
            Math.abs(rotatedX) <= stickerWidth / 2 &&
            Math.abs(rotatedY) <= stickerHeight / 2
          ) {
            setIsDraggingSticker(true);
            setSelectedStickerIndex(i);
            setDragOffset({
              x: canvasX / scaleX - sticker.x / scaleX,
              y: canvasY / scaleY - sticker.y / scaleY,
            });
            e.preventDefault();
            return;
          } else if (resizeDistance < 15) {
            // 增加检测范围
            setIsResizingSticker(true);
            setSelectedStickerIndex(i);
            setResizeStartSize(sticker.size);
            e.preventDefault();
            return;
          } else if (rotateDistance < 15) {
            // 增加检测范围
            setIsRotatingSticker(true);
            setSelectedStickerIndex(i);
            setRotateStartAngle(sticker.rotation);
            e.preventDefault();
            return;
          }
        }

        // 点击空白区域，取消选择
        onSelectText(null);
        setSelectedStickerIndex(null);
      }
    };

    // 鼠标移动事件处理函数
    const handleMouseMove = (e) => {
      if (!image) return;

      const rect = canvas.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      // 计算画布上的实际位置（考虑缩放比例）
      const scaleX = canvas.width / rect.width;
      const scaleY = canvas.height / rect.height;

      if (isDraggingSticker && selectedStickerIndex !== null) {
        // 更新贴图位置
        const newX = x * scaleX - dragOffset.x * scaleX;
        const newY = y * scaleY - dragOffset.y * scaleY;
        onStickerDrag(selectedStickerIndex, newX, newY);
      } else if (isResizingSticker && selectedStickerIndex !== null) {
        // 计算新的尺寸
        const sticker = stickers[selectedStickerIndex];
        const ctx = canvas.getContext("2d");
        const metrics = ctx.measureText(sticker.emoji);
        const stickerWidth = metrics.width;

        // 计算贴图中心点
        const centerX = sticker.x + stickerWidth / 2;
        const centerY = sticker.y - sticker.size / 2;

        // 计算鼠标到中心点的距离
        const dx = x * scaleX - centerX;
        const dy = y * scaleY - centerY;
        const distance = Math.sqrt(dx * dx + dy * dy);

        // 根据距离计算新的大小，保持最小和最大限制
        const newSize = Math.max(20, Math.min(100, distance * 1.5));
        onStickerSizeChange(selectedStickerIndex, newSize);
      } else if (isRotatingSticker && selectedStickerIndex !== null) {
        // 计算新的旋转角度
        const sticker = stickers[selectedStickerIndex];
        const ctx = canvas.getContext("2d");
        const metrics = ctx.measureText(sticker.emoji);
        const stickerWidth = metrics.width;

        // 计算贴图中心点
        const centerX = sticker.x + stickerWidth / 2;
        const centerY = sticker.y - sticker.size / 2;

        // 计算鼠标相对于中心点的角度
        const dx = x * scaleX - centerX;
        const dy = y * scaleY - centerY;
        let angle = Math.atan2(dy, dx) * (180 / Math.PI);

        // 确保角度在 0-360 度之间
        if (angle < 0) {
          angle += 360;
        }

        onStickerRotationChange(selectedStickerIndex, angle);
      } else if (dragging && selectedTextId !== null) {
        // 更新被拖拽文字的位置
        let newX = x * scaleX - dragOffset.x * scaleX;
        let newY = y * scaleY - dragOffset.y * scaleY;

        // 获取当前文本元素
        const textElem = textElements.find(
          (elem) => elem.id === selectedTextId
        );
        if (!textElem) return;

        // 获取文本尺寸信息
        const textStyle = textElem.style || {
          size: 30,
          font: "Arial",
          align: "center",
        };
        const ctx = canvas.getContext("2d");

        // 设置与绘制时相同的字体
        let fontStyle = "";
        if (textStyle.bold) fontStyle += "bold ";
        if (textStyle.italic) fontStyle += "italic ";
        ctx.font = `${fontStyle}${textStyle.size}px ${textStyle.font}`;

        // 测量文本宽度
        const metrics = ctx.measureText(textElem.text);
        const textWidth = metrics.width;
        const textHeight = textStyle.size * 1.2; // 估计文字高度

        // 根据对齐方式调整边界检查的位置偏移
        let textLeftX = newX;
        if (textStyle.align === "center") {
          textLeftX = newX - textWidth / 2;
        } else if (textStyle.align === "right") {
          textLeftX = newX - textWidth;
        }

        // 边界检查并调整 - 确保文本不会移出画布
        const padding = 5; // 边界内边距

        // 左边界检查
        if (textLeftX < padding) {
          if (textStyle.align === "center") {
            newX = textWidth / 2 + padding;
          } else if (textStyle.align === "right") {
            newX = textWidth + padding;
          } else {
            newX = padding;
          }
        }

        // 右边界检查
        if (textLeftX + textWidth > canvas.width - padding) {
          if (textStyle.align === "center") {
            newX = canvas.width - textWidth / 2 - padding;
          } else if (textStyle.align === "right") {
            newX = canvas.width - padding;
          } else {
            newX = canvas.width - textWidth - padding;
          }
        }

        // 上边界检查
        if (newY - textHeight + padding < 0) {
          newY = textHeight - padding;
        }

        // 下边界检查
        if (newY > canvas.height - padding) {
          newY = canvas.height - padding;
        }

        // 通知外部组件
        onTextDrag(selectedTextId, newX, newY);
      }
    };

    // 鼠标松开事件处理函数
    const handleMouseUp = () => {
      if (dragging) {
        setDragging(false);
      }
      if (isDraggingSticker) {
        setIsDraggingSticker(false);
      }
      if (isResizingSticker) {
        setIsResizingSticker(false);
      }
      if (isRotatingSticker) {
        setIsRotatingSticker(false);
      }
    };

    console.log("添加鼠标事件监听器");

    // 添加事件监听
    canvas.addEventListener("mousedown", handleMouseDown);
    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);

    // 清理事件监听
    return () => {
      console.log("移除鼠标事件监听器");
      canvas.removeEventListener("mousedown", handleMouseDown);
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
    };
  }, [
    dragging,
    dragOffset,
    image,
    textElements,
    selectedTextId,
    previewGif,
    onSelectText,
    onTextDrag,
    isDraggingSticker,
    selectedStickerIndex,
    stickers,
    onStickerDrag,
    onStickerSizeChange,
    onStickerRotationChange,
    isResizingSticker,
    isRotatingSticker,
  ]);

  // 检查点是否在文字区域内
  const isPointInText = (x, y, textElem) => {
    if (!textElem || !textElem.text) return false;

    const canvas = canvasRef.current;
    if (!canvas) return false;

    const ctx = canvas.getContext("2d");
    const textStyle = textElem.style;

    // 设置与绘制时相同的字体
    let fontStyle = "";
    if (textStyle.bold) fontStyle += "bold ";
    if (textStyle.italic) fontStyle += "italic ";
    ctx.font = `${fontStyle}${textStyle.size}px ${textStyle.font}`;

    const metrics = ctx.measureText(textElem.text);
    const textWidth = metrics.width;
    const textHeight = textStyle.size * 1.2; // 估计文字高度

    // 根据对齐方式计算文本框
    let textX = textElem.x;
    if (textStyle.align === "center") {
      textX = textElem.x - textWidth / 2;
    } else if (textStyle.align === "right") {
      textX = textElem.x - textWidth;
    }

    // 扩大点击区域，使拖拽更容易
    const hitAreaMargin = 15;

    // 判断点是否在文字区域
    return (
      x >= textX - hitAreaMargin &&
      x <= textX + textWidth + hitAreaMargin &&
      y >= textElem.y - textHeight - hitAreaMargin &&
      y <= textElem.y + hitAreaMargin
    );
  };

  // 分离画布尺寸设置和内容绘制
  const resizeCanvas = () => {
    const canvas = canvasRef.current;
    if (!canvas || !image) return;

    const ctx = canvas.getContext("2d");

    // 计算可见容器的宽度和高度
    const container = canvas.parentElement;
    const containerWidth = container ? container.clientWidth - 20 : 580; // 减去内边距
    const containerHeight = container ? container.clientHeight - 20 : 400; // 减去内边距

    // 计算宽高比例
    const imageRatio = image.width / image.height;
    const containerRatio = containerWidth / containerHeight;

    let canvasWidth, canvasHeight;

    // 根据容器和图片的宽高比例决定如何缩放
    if (imageRatio > containerRatio) {
      // 图片更宽，以宽度为基准
      canvasWidth = containerWidth;
      canvasHeight = containerWidth / imageRatio;
    } else {
      // 图片更高，以高度为基准
      canvasHeight = containerHeight;
      canvasWidth = containerHeight * imageRatio;
    }

    // 设置画布大小
    canvas.width = Math.floor(canvasWidth);
    canvas.height = Math.floor(canvasHeight);

    console.log(
      `Canvas resized to: ${canvas.width}x${canvas.height}, container: ${containerWidth}x${containerHeight}`
    );

    // 立即绘制内容
    drawCanvasContent();
  };

  // 只处理内容绘制，不调整尺寸
  const drawCanvasContent = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    if (image) {
      // 应用滤镜
      ctx.filter = filter || "none";

      // 绘制图片
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height);

      // 重置滤镜
      ctx.filter = "none";

      // 遍历绘制所有文字
      textElements.forEach((textElem) => {
        if (!textElem.text) return;

        const textStyle = textElem.style;

        // 设置文字样式
        let fontStyle = "";
        if (textStyle.bold) fontStyle += "bold ";
        if (textStyle.italic) fontStyle += "italic ";
        ctx.font = `${fontStyle}${textStyle.size}px ${textStyle.font}`;
        ctx.fillStyle = textStyle.color;
        ctx.strokeStyle = textStyle.strokeColor;
        ctx.lineWidth = textStyle.strokeWidth;
        ctx.textAlign = textStyle.align;

        // 应用阴影效果
        if (textStyle.shadow) {
          ctx.shadowColor = textStyle.shadowColor;
          ctx.shadowBlur = textStyle.shadowBlur;
          ctx.shadowOffsetX = textStyle.shadowOffsetX;
          ctx.shadowOffsetY = textStyle.shadowOffsetY;
        } else {
          ctx.shadowColor = "transparent";
          ctx.shadowBlur = 0;
          ctx.shadowOffsetX = 0;
          ctx.shadowOffsetY = 0;
        }

        // 绘制文字
        ctx.strokeText(textElem.text, textElem.x, textElem.y);
        ctx.fillText(textElem.text, textElem.x, textElem.y);

        // 如果是选中的文字，绘制选中指示器
        if (
          selectedTextId === textElem.id ||
          (dragging && selectedTextId === textElem.id)
        ) {
          drawDragIndicator(ctx, textElem);
        }

        // 重置阴影
        ctx.shadowColor = "transparent";
        ctx.shadowBlur = 0;
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
      });

      // 绘制贴图
      stickers.forEach((sticker, index) => {
        ctx.save();

        // 设置贴图位置和旋转
        ctx.translate(
          sticker.x + ctx.measureText(sticker.emoji).width / 2,
          sticker.y - sticker.size / 2
        );
        ctx.rotate((sticker.rotation * Math.PI) / 180);
        ctx.translate(
          -ctx.measureText(sticker.emoji).width / 2,
          sticker.size / 2
        );

        // 绘制贴图
        ctx.font = `${sticker.size}px serif`;
        ctx.fillText(sticker.emoji, 0, 0);

        // 如果是选中的贴图，绘制控制点
        if (index === selectedStickerIndex) {
          const metrics = ctx.measureText(sticker.emoji);
          const stickerWidth = metrics.width;
          const stickerHeight = sticker.size;

          // 绘制选中框
          ctx.strokeStyle = "#4285f4";
          ctx.lineWidth = 2;
          ctx.setLineDash([5, 3]);
          ctx.strokeRect(
            -stickerWidth / 2 - 5,
            -stickerHeight + 5,
            stickerWidth + 10,
            stickerHeight + 5
          );

          // 绘制调整大小的控制点
          ctx.fillStyle = "#4285f4";
          ctx.beginPath();
          ctx.arc(stickerWidth / 2 + 15, 0, 8, 0, Math.PI * 2);
          ctx.fill();
          // 添加白色边框
          ctx.strokeStyle = "#ffffff";
          ctx.lineWidth = 2;
          ctx.stroke();
          // 添加内部白色圆点
          ctx.fillStyle = "#ffffff";
          ctx.beginPath();
          ctx.arc(stickerWidth / 2 + 15, 0, 4, 0, Math.PI * 2);
          ctx.fill();

          // 绘制旋转的控制点
          ctx.fillStyle = "#4285f4";
          ctx.beginPath();
          ctx.arc(0, -stickerHeight / 2 - 25, 8, 0, Math.PI * 2);
          ctx.fill();
          // 添加白色边框
          ctx.strokeStyle = "#ffffff";
          ctx.lineWidth = 2;
          ctx.stroke();
          // 添加内部白色圆点
          ctx.fillStyle = "#ffffff";
          ctx.beginPath();
          ctx.arc(0, -stickerHeight / 2 - 25, 4, 0, Math.PI * 2);
          ctx.fill();

          // 绘制连接线
          ctx.beginPath();
          ctx.moveTo(stickerWidth / 2 + 15, 0);
          ctx.lineTo(0, -stickerHeight / 2 - 25);
          ctx.strokeStyle = "#4285f4";
          ctx.lineWidth = 1;
          ctx.setLineDash([3, 3]);
          ctx.stroke();
        }

        ctx.restore();
      });
    } else {
      // 默认空白画布
      canvas.width = 500;
      canvas.height = 500;
      ctx.fillStyle = "#eee";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    }
  };

  // 重命名原来的函数，使其调用新的分离函数
  const drawCanvas = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    if (!image) {
      // 默认空白画布
      canvas.width = 500;
      canvas.height = 400;
      const ctx = canvas.getContext("2d");
      ctx.fillStyle = "#f5f5f5";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      return;
    }

    // 拖拽过程中不调整画布尺寸，只重绘内容
    if (dragging) {
      drawCanvasContent();
    } else {
      // 非拖拽状态下，如有必要可重设尺寸
      drawCanvasContent();
    }
  };

  // 绘制文字拖拽指示器
  const drawDragIndicator = (ctx, textElem) => {
    // 保存当前上下文状态
    ctx.save();

    // 设置指示器样式
    ctx.strokeStyle = "#4285f4";
    ctx.lineWidth = 2;
    ctx.setLineDash([5, 3]);

    // 计算文本宽度和高度
    const metrics = ctx.measureText(textElem.text);
    const textWidth = metrics.width;
    const textHeight = textElem.style.size * 1.2; // 估计文字高度

    // 根据对齐方式调整矩形位置
    let rectX = textElem.x;
    if (textElem.style.align === "center") {
      rectX = textElem.x - textWidth / 2;
    } else if (textElem.style.align === "right") {
      rectX = textElem.x - textWidth;
    }

    // 绘制矩形框
    ctx.strokeRect(
      rectX - 5,
      textElem.y - textHeight + 5,
      textWidth + 10,
      textHeight + 5
    );

    // 恢复上下文状态
    ctx.restore();
  };

  const handleDownload = () => {
    downloadImage(canvasRef.current);
  };

  // 创建仅包含原始图像（无文字）的画布
  const createOriginalImageCanvas = async () => {
    if (!originalImageRef.current) return null;

    // 创建临时画布
    const tempCanvas = document.createElement("canvas");
    const img = originalImageRef.current;

    // 使用原始图像尺寸
    tempCanvas.width = img.width;
    tempCanvas.height = img.height;

    // 绘制原始图像（无文字）
    const ctx = tempCanvas.getContext("2d");

    // 应用滤镜
    ctx.filter = filter || "none";
    ctx.drawImage(img, 0, 0, img.width, img.height);

    // 将画布转换为Blob
    return new Promise((resolve) => {
      tempCanvas.toBlob(resolve, "image/png");
    });
  };

  // 服务器生成GIF
  const handleGenerateServerGif = async () => {
    if (!image) {
      alert("请先上传或选择图片");
      return;
    }

    setGeneratingGif(true);
    try {
      const canvas = canvasRef.current;

      // 直接从当前画布创建包含所有文字的Blob
      const displayCanvas = document.createElement("canvas");
      displayCanvas.width = canvas.width;
      displayCanvas.height = canvas.height;
      const displayCtx = displayCanvas.getContext("2d");

      // 复制当前画布内容（包括所有文字）
      displayCtx.drawImage(canvas, 0, 0);

      // 获取当前画布的展示尺寸
      const canvasDisplayBlob = await new Promise((resolve) => {
        displayCanvas.toBlob(resolve, "image/png");
      });

      if (!canvasDisplayBlob) {
        throw new Error("无法处理图像");
      }

      // 获取原始图像（用于生成GIF）
      const originalImageBlob = await createOriginalImageCanvas();
      if (!originalImageBlob) {
        throw new Error("无法处理原始图像");
      }

      // 计算比例 - 画布上的坐标与原始图像坐标的比例
      const displayRatio = canvas.width / image.width;
      console.log(
        `显示比例: ${displayRatio}, 画布: ${canvas.width}x${canvas.height}, 原图: ${image.width}x${image.height}`
      );

      // 创建FormData
      const formData = new FormData();
      formData.append("image", originalImageBlob, "meme.png"); // 原始图像
      formData.append("displayImage", canvasDisplayBlob, "display.png"); // 带文字的显示图像

      // 使用新的多文本GIF生成API，基于当前的文本元素
      const serviceTextElements = textElements.map((textElem) => {
        // 向服务器发送画布上确切的文本位置
        const backendX = Math.round(textElem.x / displayRatio);
        const backendY = Math.round(textElem.y / displayRatio);
        const style = textElem.style;

        return {
          text: textElem.text,
          x: backendX,
          y: backendY,
          align: style.align || "center",
          fontFamily: style.font || "Arial",
          fontSize: Math.round(style.size / displayRatio),
          fontColor: style.color || "#FFFFFF",
          strokeColor: style.strokeColor || "#000000",
          strokeWidth: Math.round(style.strokeWidth / displayRatio),
          bold: style.bold !== undefined ? style.bold : false,
          italic: style.italic !== undefined ? style.italic : false,
          hasShadow: style.shadow !== undefined ? style.shadow : false,
          shadowColor: style.shadowColor || "#000000",
          shadowBlur: Math.round((style.shadowBlur || 0) / displayRatio),
          shadowOffsetX: Math.round((style.shadowOffsetX || 0) / displayRatio),
          shadowOffsetY: Math.round((style.shadowOffsetY || 0) / displayRatio),
          animation: style.animation || "bounce", // 添加动画类型
        };
      });

      // 将文本元素数组转换为JSON字符串
      formData.append("textElements", JSON.stringify(serviceTextElements));

      // 添加画布尺寸信息
      formData.append("canvasWidth", canvas.width);
      formData.append("canvasHeight", canvas.height);
      formData.append("imageWidth", image.width);
      formData.append("imageHeight", image.height);
      formData.append("displayRatio", displayRatio);

      // 添加GIF生成参数
      formData.append("frames", 20); // 帧数
      formData.append("delay", 100); // 帧间延迟(毫秒)
      formData.append("animationType", "separate"); // 使用单独动画标记
      formData.append("preserveAspectRatio", "true"); // 保持宽高比
      formData.append("matchDisplaySize", "true"); // 匹配显示尺寸

      // 调用API获取GIF
      const response = await generateGifFromServer(formData);

      if (response && response.gifUrl) {
        setPreviewGif(response.gifUrl);
      } else {
        throw new Error("服务器未返回有效的GIF URL");
      }
    } catch (error) {
      console.error("生成动画GIF失败:", error);
      alert("生成动画GIF失败: " + (error.message || "未知错误"));
    } finally {
      setGeneratingGif(false);
    }
  };

  // 下载预览的GIF
  const handleDownloadGif = () => {
    if (previewGif) {
      // 创建一个fetch请求获取Blob数据
      fetch(previewGif)
        .then((response) => response.blob())
        .then((blob) => {
          // 使用saveAs函数下载Blob
          saveAs(blob, "meme.gif");
        })
        .catch((error) => {
          console.error("下载GIF失败:", error);
          alert("下载GIF失败，请稍后重试");
        });
    }
  };

  const handleShare = async () => {
    try {
      const blob = await new Promise((resolve) => {
        canvasRef.current.toBlob(resolve);
      });

      if (navigator.share) {
        await navigator.share({
          title: "我制作的表情包",
          files: [new File([blob], "meme.png", { type: "image/png" })],
        });
      } else {
        handleDownload();
      }
    } catch (err) {
      console.error("分享失败:", err);
      alert("分享失败，请尝试下载后分享");
    }
  };

  const handleGenerate = () => {
    if (onGenerate) {
      onGenerate(canvasRef.current);
    }
  };

  const handleClosePreview = () => {
    setPreviewGif(null);

    // 确保拖拽状态重置
    setDragging(false);
    setIsDraggingSticker(false);
    setIsResizingSticker(false);
    setIsRotatingSticker(false);

    // 确保画布被重新绘制并正确设置尺寸
    setTimeout(() => {
      resizeCanvas();

      // 设置一个标志，强制画布在下一帧重绘
      const canvas = canvasRef.current;
      if (canvas) {
        const ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        drawCanvasContent();
      }
    }, 50);
  };

  return (
    <div className="meme-canvas-container">
      {/* 渲染预览GIF或静态画布 */}
      {previewGif ? (
        <div className="canvas-wrapper">
          <img
            src={previewGif}
            alt="GIF Preview"
            className="gif-preview"
            style={{
              maxWidth: "100%",
              maxHeight: "100%",
              width: "auto",
              height: "auto",
              display: "block",
              margin: "auto",
            }}
          />
          <div className="preview-controls">
            <button className="close-preview" onClick={handleClosePreview}>
              返回编辑
            </button>
          </div>
        </div>
      ) : (
        <div className={`canvas-wrapper ${!image ? "empty-canvas" : ""}`}>
          <canvas
            ref={canvasRef}
            onClick={(e) =>
              !dragging &&
              !isDraggingSticker &&
              !isResizingSticker &&
              !isRotatingSticker &&
              onCanvasClick &&
              onCanvasClick(e)
            }
            className={`meme-canvas ${
              dragging ||
              isDraggingSticker ||
              isResizingSticker ||
              isRotatingSticker
                ? "dragging"
                : ""
            }`}
            style={{
              cursor:
                dragging || isDraggingSticker
                  ? "move"
                  : isResizingSticker
                  ? "nwse-resize"
                  : isRotatingSticker
                  ? "crosshair"
                  : "default",
              maxWidth: "100%",
              maxHeight: "100%",
              display: "block",
              margin: "auto",
            }}
          />
          {!image && (
            <div className="empty-canvas-hint">
              <p>请上传图片或选择模板开始创建</p>
            </div>
          )}
          {image && (
            <div className="drag-tip">
              提示：点击文字或贴图可选中，拖动可调整位置，拖动控制点可调整大小和旋转
            </div>
          )}
        </div>
      )}

      {/* 将按钮区域放在容器最下方，使其能固定在可视区域底部 */}
      <div className="canvas-actions">
        {image ? (
          <>
            <button onClick={handleGenerateServerGif} disabled={generatingGif}>
              {generatingGif ? "生成中..." : "生成GIF"}
            </button>
            <button onClick={handleGenerate} disabled={generating}>
              {generating ? "处理中..." : "保存至服务器"}
            </button>
            <button onClick={handleDownload}>下载图片</button>
            {previewGif && (
              <button
                onClick={handleDownloadGif}
                className="download-gif-button"
              >
                下载GIF
              </button>
            )}
            <button onClick={handleShare}>分享</button>
          </>
        ) : (
          <>
            <button onClick={handleGenerateServerGif} disabled={!image}>
              生成GIF
            </button>
            <button onClick={handleGenerate} disabled={!image}>
              保存至服务器
            </button>
            <button onClick={handleDownload} disabled={!image}>
              下载图片
            </button>
            <button onClick={handleShare} disabled={!image}>
              分享
            </button>
          </>
        )}
      </div>
    </div>
  );
};

export default MemeCanvas;
